﻿package
{
	import flash.data.*;
	import flash.events.SQLEvent;
	import flash.events.SQLErrorEvent;
	import flash.filesystem.File; 

	class SQL extends Object
	{
		private var dbFile:File;
		private var conn:SQLConnection;
		
		public function SQL(db:String, createMe:String) 
		{
			trace(parent);
			if (conn == null) 
			{
				conn = new SQLConnection(); 
					 
				conn.addEventListener(SQLEvent.OPEN, openHandler); 
				conn.addEventListener(SQLEvent.RESULT, getResults); 
				conn.addEventListener(SQLErrorEvent.ERROR, errorHandler); 
					 
				// The database file is in the application storage directory 
				dbFile = File.applicationStorageDirectory.resolvePath(db); 
				
				if(!dbFile.exists)
				{
					conn.open(dbFile, SQLMode.CREATE);
					conn.close();
				}
				conn.open(dbFile, SQLMode.UPDATE);

				var sqlStatement:SQLStatement = new SQLStatement();
				sqlStatement.addEventListener(SQLErrorEvent.ERROR, errorHandler);
				sqlStatement.sqlConnection = conn;
				sqlStatement.text = 'Create Table If Not Exists '+createMe;
				sqlStatement.execute();

			}
		}

		public function execute_query(sql)
		{
			SQL(null);
			var sqlStatement:SQLStatement = new SQLStatement();
			sqlStatement.sqlConnection = conn;
			sqlStatement.text = sql;
			sqlStatement.execute();
			return sqlStatement.getResult().data;
		}
		
		
		function openHandler(event:SQLEvent):void 
		{ 
			//trace("the database was created successfully"); 
		} 
			 
		function errorHandler(event:SQLErrorEvent):void 
		{ 
			new Errors("Error message: "+event.error.message+"\nDetails: "+event.error.details); 
		} 
	}
}